//
// Created by LiuYou on 2021/8/4.
//

#include <cstdio>
#include <cstdlib>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <iostream>
#include "Proto.hpp"


/*
 * sender方负责创建多播组
 */
int main(int argc, char** argv) {
    int socketFD = socket( PF_INET, SOCK_DGRAM, 0 );
    if (socketFD < 0) {
        perror( "socket()" );
        exit( 1 );
    }

    // 创建多播组, 发送组间消息

    struct ip_mreq ipMultiCastRequest{};
    // 多播组的IP地址
    inet_pton( AF_INET, MC_GROUP, &ipMultiCastRequest.imr_multiaddr );
    // 当前你自己的IP地址
    inet_pton( AF_INET, "0.0.0.0", &ipMultiCastRequest.imr_interface );
    int retVal = setsockopt( socketFD, IPPROTO_IP, IP_MULTICAST_IF,
                             &ipMultiCastRequest, sizeof( ipMultiCastRequest ));
    if (retVal < 0) {
        perror( "setsockopt()" );
        exit( 1 );
    }

//    bind();

    using SocketBasic::Msg;
    Msg sendMsg( "Alan", htonl((rand() % 100)), htonl((rand() % 100)));
    struct sockaddr_in remoteAddress{
            .sin_family=AF_INET,
            .sin_port=htons( atoi( RCV_PORT ))
    };
    inet_pton( AF_INET, MC_GROUP, &remoteAddress.sin_addr );
    ssize_t ret = sendto( socketFD, &sendMsg, sizeof( sendMsg ), 0,
                          (sockaddr*) &remoteAddress, sizeof( remoteAddress ));
    if (ret < 0) {
        perror( "sendto()" );
        exit( 1 );
    }
    puts( "OK!" );
    close( socketFD );

    exit( 0 );
}